I needed to write a simple PHP utility script for importing my UBB.classic avatars into UBB.threads. I prefer running such scripts from the shell (command line), so I don't have to deal with CGI timeouts, etc. I could have used Perl instead, but I'm missing the Perl DBI module for interfacing with MySQL, and didn't want to mess with installing it right now.
You would think that reading and writing stuff to the console would be easy (as it is in Perl or C), but it took me a couple of hours to figure out how to do it in PHP. There were mainly two things I had to do:
1) Call ob_implicit_flush() before doing any I/O. This causes the output buffer to be automatically flushed each time output is performed.
2) Explicitly open standard input. Here's a function I wrote for doing the input. The function readline() supposedly does about the same thing, but that's apparently part of an add-on module that has to be compiled into PHP.
code:
// Output a prompt string to the console,
// and get the (whitespace-trimmed) response.
function getline($prompt) {
echo $prompt;
$fp = fopen('php://stdin', 'r') or die("fopen(stdin)\n");
$line = fgets($fp, 1024);
fclose($fp);
return trim($line);
}
If anyone knows an easier way of doing this, please correct me.
